<?php

use Doraemon\service\statSign\Basic as statSign;
use Doraemon\tools\Youzan;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;

class GoodsListV2Action extends ActionPlugin
{
    public const USER_LEVEL = self::LEVEL_NOTHING;

    private $actFrom = 'app';
    private $ver = 2;
    private $couponEndTime = '2022-12-08';

    /**
     * @throws Exception
     */
    public function main()
    {

        $this->actFrom = $this->getRequest()->getQuery('act_from', 'app');
        $ver = $this->getRequest()->getQuery('ver', 2);
        $this->ver = $ver;
        if (3 == $this->ver) {
            $this->couponEndTime = '2023-03-14';
        }

        $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_GOODS);
        $data = $redis->getCache($ver);

        $couponData = $data['coupon_data'] ?? [];
        $todayData = $data['today_data'] ?? [];
        $categoryData = $data['category_data'] ?? [];

        $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_SUBSCRIBE);
        $subKeyPrefix = 'v2-' . $this->uid . '-20221201';
        $subRes = $redis->getCache($subKeyPrefix);
        $isSubscribe = $subRes['subscribe'] ?? false;
        $isSubscribe = $isSubscribe ? true : false;

        [$category, $categoryList] = $this->getCategoryList($categoryData);
        $result = [
            'coupon_info' => $this->getCouponInfo($couponData),
            'today_list' => $this->getGoodsList($todayData, 1),
            'category' => $category,
            'category_list' => $categoryList,
            'is_subscribe' => $isSubscribe ? 1 : 0
        ];
        if (3 == $this->ver) {
            $result['topic'] = $this->getTopic();
        }
        $this->setSuccess($result);
    }

    private function getTopic()
    {
        $result = [];
        if (3 == $this->ver) {
            $topicId = 2090;
            $result = [
                'topic_id' => $topicId,
                'statSign' => statSign::genStatSign(statSign::MODULE_SUBSIDY_DAY_V3_TOPIC_CARD, [
                    statSign::EXTEND_KEY_OBJ_ID => 3,
                    statSign::EXTEND_KEY_OBJ_TYPE => \Doraemon\tools\BlockType::TYPE_TOPIC_ACTIVITY,
                    statSign::EXTEND_KEY_ACTIVITY_NAME => 'subsidy_day'
                ], ['activity_name' => 'subsidy_day'])];
        }
        return $result;
    }

    private function getCategoryList($categoryData)
    {
        $categoryDescArr = [
            //v2
            '清洁好物' => [
                'title' => '意外好用的清洁好物',
                'sub_title' => '找对好帮手，家务事半功倍',
            ],
            '生活家电' => [
                'title' => '不后悔入手的家电',
                'sub_title' => '大幅提升居家幸福感',
            ],
            '居家日用' => [
                'title' => '不后悔入手的家电',
                'sub_title' => '大幅提升居家幸福感',
            ],
            '床品家纺' => [
                'title' => '不后悔入手的家电',
                'sub_title' => '大幅提升居家幸福感',
            ],
            //v3
            '生活日用' => [
                'title' => '意外好用的生活日用',
                'sub_title' => '花小钱大幅提升居家幸福感',
            ],
            '家用电器' => [
                'title' => '相见恨晚的家用电器',
                'sub_title' => '用了就知道生活可以如此便利',
            ],
            '床品' => [
                'title' => '舒适治愈的换季床品',
                'sub_title' => '让宅家满满松弛感',
            ],
            '灯饰灯具' => [
                'title' => '氛围感灯饰',
                'sub_title' => '点亮夜晚 点亮生活',
            ],
            '家具' => [
                'title' => '令人心动的宝藏家具',
                'sub_title' => '颜值与实用性并存',
            ],
        ];
        if ($categoryData) {
            shuffle($categoryData);
        }
        $list = [];
        $category = [];
        foreach ($categoryData as $row) {
            $goodsList = $this->getGoodsList($row['list'], 2, $row['category']);
            if (!empty($goodsList)) {
                $list[] = [
                    'category_id' => $row['category_id'],
                    'category' => $row['category'],
                    'title' => $categoryDescArr[$row['category']]['title'] ?? '',
                    'sub_title' => $categoryDescArr[$row['category']]['sub_title'] ?? '',
                    'list' => $goodsList,
                ];
                $category[] = [
                    'category_id' => $row['category_id'],
                    'category' => $row['category'],
                ];
            }
        }
        return [$category, $list];
    }

    /**
     * @param $dataList 商品数据
     * @param $type 1：今日住友推荐商品列表 2：分类下商品列表
     * @return array
     */
    private function getGoodsList($dataList, $type, $category = '今日住友推荐')
    {
        if ($dataList) {
            shuffle($dataList);
        }
        $data = [];
        foreach ($dataList as $key => $row) {
            if (3 == $this->ver) {
                $statSign = statSign::genStatSign(statSign::MODULE_SUBSIDY_DAY_V3_BANNER, [
                    statSign::EXTEND_KEY_OBJ_ID => $row['alias'],
                    statSign::EXTEND_KEY_ACTIVITY_NAME => 'subsidy_day'
                ], ['activity_name' => 'subsidy_day', 'information' => $row['title'], 'tab' => $category]);
            } else {
                $statSign = statSign::genStatSign(statSign::MODULE_SUBSIDY_DAY_V2_BANNER, [
                    statSign::EXTEND_KEY_OBJ_ID => $row['alias'],
                    statSign::EXTEND_KEY_ACTIVITY_NAME => 'subsidy_day'
                ], ['activity_name' => 'subsidy_day', 'information' => $row['title'], 'tab' => $category]);
            }
            $itemId = $row['item_id'];
            $data[$key] = $row;
            $data[$key]['stock'] = $this->getGoodsStock($itemId);
            $data[$key]['open_wechat_mini_link'] = $this->getLink($row['original_link'], $row['wechat_mini_link']);
            $data[$key]['statSign'] = $statSign;
        }
        $arr = [];
        $posArr = [];
        foreach ($data as $row) {
            if ($row['stock']) {
                if ($row['pos'] > 0) {
                    $posArr[] = $row;
                } else {
                    $arr[] = $row;
                }
            }
        }
        if ($posArr) {
            $sortPos = array_column($posArr, 'pos');
            array_multisort($sortPos, SORT_ASC, $posArr);
            foreach ($posArr as $row) {
                $pos = $row['pos'];
                array_splice($arr, ($pos - 1), 0, [$row]);
            }
        }
        return $arr;
    }

    private function getCouponInfo($couponData)
    {
        $today = date('Y-m-d');
        $couponInfo = null;
        $couponId = 0;
        if (strtotime($today) < strtotime($this->couponEndTime)) {
            foreach ($couponData as $row) {
                $receiveDate = date('Y-m-d', strtotime($row['receive_date']));
                if ($receiveDate == $today) {
                    $couponId = $row['coupon_id'];
                    $couponInfo = $row;
                    break;
                }
            }
            if ($couponInfo) {
                $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_COUPON_STOCK);
                $cacheStock = $redis->getCache($couponId);
                if (empty($cacheStock)) {
                    $cacheStock = [
                        'coupon_id' => $couponId,
                        'stock' => 0,
                    ];
                    $couponDetail = Youzan::getCouponDetail($couponId);
                    if ($couponDetail) {
                        $cacheStock['stock'] = $couponDetail['stock_qty'] ?? 0;//缓存优惠券库存 1个小时
                    }
                    $minute = rand(58, 65);
                    $redis->setCache($cacheStock, $couponId);
                    $redis->setExpireTime($minute * 60, $couponId);//缓存优惠券库存 1个小时
                }
                $couponInfo['stock'] = $cacheStock['stock'];
                $couponInfo['open_wechat_mini_link'] = $this->getLink($couponInfo['original_link'], $couponInfo['wechat_mini_link']);
                $couponInfo['statSign'] = '';
//                if ($couponInfo['stock'] <= 1) {
//                    unset($couponInfo['wechat_mini_link']);
//                    unset($couponInfo['original_link']);
//                    unset($couponInfo['open_wechat_mini_link']);
//                }
            }
        }
        return $couponInfo;
    }

    private function getGoodsStock($itemId)
    {
        $redis = new newCache(redisKeys::KEY_B_CACHE_SUPER_SUBSIDY_DAY_ITEM_STOCK);
        $cacheStock = $redis->getCache($itemId);
        if (empty($cacheStock)) {
            $cacheStock = [
                'item_id' => $itemId,
                'stock' => 0,
            ];
            $goodsInfo = Youzan::getItemDeatil($itemId);
            if ($goodsInfo) {
                $cacheStock['stock'] = $goodsInfo['quantity'] ?? 0;//缓存商品库存 1个小时
            }
            $minute = rand(58, 65);
            $redis->setCache($cacheStock, $itemId);
            $redis->setExpireTime($minute * 60, $itemId);//缓存秒杀商品库存和时间 1个小时
        }
        return $cacheStock['stock'] ?? 0;
    }

    private function getLink($originalLink, $wechatLink)
    {
        $fallback = $originalLink ? 'niceliving://webview/normalscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $originalLink]))) : '';
        $jsonData = [
            'id' => 'gh_b1ae1477aad9',
            'path' => $wechatLink,
            'fallback' => $fallback
        ];
        $open_wechat_mini_link = 'niceliving://open/wechat_miniprogram?protego=' . urlencode(base64_encode(json_encode($jsonData)));
        return $open_wechat_mini_link;
    }

}